package com.djf.word.controller;

/**
 * @Author 26393
 * @Date 2025/7/9 18:35
 * @Version 1.0
 */
import com.alibaba.excel.EasyExcel;
import com.djf.word.entity.ImportErrorRow;
import com.djf.word.entity.Order;
import com.djf.word.entity.OrderExcelProgress;
import com.djf.word.listener.OrderExportExcelHandler;
import com.djf.word.listener.OrderImportListener;
import com.djf.word.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/api/order/excel")
public class OrderExcelController {

    @Autowired
    private OrderService orderService;

    private static final ConcurrentHashMap<String, OrderExcelProgress> progressMap
            = new ConcurrentHashMap<>();

    /**
     * 导出订单（支持大数据量）
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response, @RequestParam String progressId) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("订单数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        OrderExcelProgress progress = new OrderExcelProgress();
        progress.setStartTime(System.currentTimeMillis());
        progress.setProgress(0.0);
        progress.setMessage("导出开始");
        progressMap.put(progressId, progress);

        new OrderExportExcelHandler(orderService, progressMap)
                .export(response.getOutputStream(), progress, progressId);
    }

    /**
     * 导入订单（支持大数据量）
     * 前端需先读取文件行数并传参 totalRows
     */
    /**
     * 导入订单（自动统计总行数+错误反馈）
     */
    @PostMapping("/import")
    public HashMap<String, Object> importOrder(@RequestParam("file") MultipartFile file,
                                               @RequestParam String progressId) throws Exception {
        OrderExcelProgress progress = new OrderExcelProgress();
        progress.setStartTime(System.currentTimeMillis());
        progress.setProgress(0.0);
        progress.setMessage("导入开始");
        progressMap.put(progressId, progress);

        OrderImportListener listener = new OrderImportListener(orderService, progress, progressId, progressMap);
        EasyExcel.read(file.getInputStream(), Order.class, listener)
                .sheet()
                .doRead();

        List<ImportErrorRow> errorRows = listener.getErrorRows();
        HashMap<String, Object> result = new HashMap<>();
        result.put("success", errorRows.isEmpty());
        result.put("errorRows", errorRows);
        result.put("total", progress.getProgress());
        result.put("msg", errorRows.isEmpty() ? "导入完成" : "部分行导入失败");
        return result;
    }

    /**
     * 查询导入/导出进度
     */
    @GetMapping("/progress")
    public OrderExcelProgress getProgress(@RequestParam String progressId) {
        return progressMap.getOrDefault(progressId, new OrderExcelProgress());
    }
}
